<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="clickExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="username" sortable="">
            <template v-slot="{row}">
              <img v-imgerror="defaultImg" :src="row.staffPhoto ||defaultImg" alt="" class="staff" @click="abc(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ formateTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button :disabled="!checkButton('look')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assginRole(row.id)">角色</el-button>
              <el-button :disabled="!checkButton('delete')" type="text" size="small" @click="reqDelEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" />
    <el-dialog :visible.sync="showCode" title="二维码" width="300px">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeDialog" @open="handleOpen">
      <el-checkbox-group v-model="checkList" v-loading="loading1">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div style="text-align: right">
          <el-button type="primary" @click="clickSubmit">确定</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetEmployeeList, reqDelEmployee, reqGetUserDetailById, reqAssignRoles } from '@/api/employee'
import EmployeeEnum from '@/api/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import defaultImg from '@/assets/common/bigUserHeader.png'
import QrCode from 'qrcode'
export default {
  name: 'Employees',
  components: { addEmployee },
  data() {
    return {
      list: [],
      page: 1, // 当前页
      pageSize: 10, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false,
      defaultImg,
      showCode: false,
      showRoleDialog: false,
      roleList: [],
      checkList: [],
      userId: '',
      loading1: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    checkButton(type) {
      const points = this.$store.state.user.userInfo.roles.points
      // console.log(points)
      return points.includes(type)
    },
    async getEmployeeList() {
      this.loading = true
      const { data } = await reqGetEmployeeList(this.page, this.pageSize)
      const { total, rows } = data
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    formateTime(time) {
      return dayjs(time).format('YYYY年MM日DD日')
    },
    async reqDelEmployee(id) {
      const res = await this.$confirm('确定要删除吗?', '提示').catch(error => error)
      if (res !== 'confirm') return
      await reqDelEmployee(id)
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    clickExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }

        const { data: { rows }} = await reqGetEmployeeList(1, this.total)
        // console.log(rows)

        const arr = []
        rows.forEach(item => {
          const newArr = []
          headersArr.forEach(v => {
            const enkey = headersRelations[v]
            if (enkey === 'formOfEmployment') {
              const obj = EmployeeEnum.hireType.find(value => value.id === +item[enkey])
              const res = obj ? obj.value : '未知'
              newArr.push(res)
            } else {
              newArr.push(item[enkey])
            }
            // newArr.push(item[enkey])
          })
          arr.push(newArr)
        })
        console.log(arr)

        excel.export_json_to_excel({
          header: headersArr,
          data: arr,
          filename: '信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    abc(data) {
      if (!data) return
      this.showCode = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, data)
      })
    },
    assginRole(id) {
      this.showRoleDialog = true
      // console.log(id)
      this.userId = id
    },
    handleOpen() {
      this.loading1 = true
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading1 = false
      })
    },
    closeDialog() {
      this.showRoleDialog = false
      this.checkList = []
    },
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 1000)
      // console.log(rows)
      this.roleList = rows
    },
    async getUserDetailById() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      // console.log(roleIds)
      this.checkList = roleIds || []
    },
    async clickSubmit() {
      await reqAssignRoles({ id: this.userId, roleIds: this.checkList })
      this.$message.success('分配角色成功')
      this.closeDialog()
    }
  }
}
</script>

<style lang="scss">
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
